package com.nbgroup.web.identity;

import com.nbgroup.entity.Identity.Identity;
import com.nbgroup.entity.User;
import com.nbgroup.entity.dayvisitors;
import com.nbgroup.service.DayVisitorsService;
import com.nbgroup.service.Identity.IdentityService;
import com.nbgroup.utils.PageUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.WorkbookUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 顾志杰 on 2018/8/15.
 */
@Controller
@RequestMapping(value = "identity")
public class IdentityController {
    @Autowired
    private IdentityService identityService;
    @Autowired
    private DayVisitorsService dayVisitorsService;


    @GetMapping("toIdentityList")
    public String identityList(Map<String, Object> map, Identity identity, Integer page, Integer pageSize) {
        if (StringUtils.isNotBlank(identity.getIdentityId())) {
            map.put("identityId", identity.getIdentityId().replace(" ", ""));
        }
        if (StringUtils.isNotBlank(identity.getName())) {
            map.put("name", identity.getName().trim());
        }
        if (StringUtils.isNotBlank(identity.getSex())) {
            map.put("sex", identity.getSex().trim());
        }
        if (StringUtils.isNotBlank(identity.getNation())) {
            map.put("nation", identity.getNation().trim());
        }
        if (StringUtils.isNotBlank(identity.getMaxAge())) {
            map.put("maxAge", identity.getMaxAge().trim());
        }
        if (StringUtils.isNotBlank(identity.getMinAge())) {
            map.put("minAge", identity.getMinAge().trim());
        }
        if (StringUtils.isNotBlank(identity.getAddress())) {
            map.put("address", identity.getAddress().trim());
        }
        if (StringUtils.isNotBlank(identity.getAgencyUnit())) {
            map.put("agencyUnit", identity.getAgencyUnit().trim());
        }
        if (StringUtils.isNotBlank(identity.getPhysicalCardNumber())) {
            map.put("physicalCardNumber", identity.getPhysicalCardNumber().trim());
        }
        if (StringUtils.isNotBlank(identity.getMinEarliestDate())) {
            map.put("minEarliestDate", identity.getMinEarliestDate());
        }
        if (StringUtils.isNotBlank(identity.getMaxEarliestDate())) {
            map.put("maxEarliestDate", identity.getMaxEarliestDate());
        }
        if (StringUtils.isNotBlank(identity.getMinRecentDate())) {
            map.put("minRecentDate", identity.getMinRecentDate());
        }
        if (StringUtils.isNotBlank(identity.getMaxRecentDate())) {
            map.put("maxRecentDate", identity.getMaxRecentDate());
        }
        PageUtil<Identity> identityList = identityService.findAllByPage(identity, page, pageSize);
        map.put("datas", identityList);
        return "push";
    }

    @GetMapping(value = "exportExcel")
    public void exportExcel(String identityId, String name, String sex, String nation, String maxAge, String minAge, String address, String minRecentDate, String maxRecentDate, HttpServletResponse response) throws IOException {
        String fileName = "游客信息.xls";
        String[] columnName = {"序号", "姓名", "身份证", "性别", "民族", "出生", "住址", "最近到馆时间"};
        Identity identity = new Identity();
        identity.setIdentityId(identityId);
        identity.setName(name);
        if (!("undefined".equals(sex))) {
            identity.setSex(sex);
        }
        identity.setNation(nation);
        identity.setMaxAge(maxAge);
        identity.setMinAge(minAge);
        identity.setAddress(address);
        if (StringUtils.isNoneEmpty(minRecentDate)) {
            identity.setMinRecentDate(minRecentDate + " 00:00:00");
        }
        if (StringUtils.isNoneEmpty(maxRecentDate)) {
            identity.setMaxRecentDate(maxRecentDate + " 23:59:59");
        }

        List<Identity> content = identityService.findAllByPage(identity, 1, 99999999).getContent();
//        List<PopulationExcel> regionEvaluatelList = populationService.findAllForExportExcel(qualifications, tel, marryStatus, minAge, maxAge, orgId, gridId, buildingId, name, idcardno, leaguer, birthBegTime, birthEndTime, sex, nation, politicalStatus, residenceType, 1, 999999999).getContent();


        regionExport(response, columnName, fileName, content);

    }

    private void regionExport(HttpServletResponse response, String[] columnName, String fileName, List<Identity> regionEvaluatelList) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //你可以使用org.apache.poi.ss.util.WorkbookUtil＃createSafeSheetName（String nameProposal）}
        //用于创建有效名称的安全方法，此实用程序用空格（''）替换无效字符
        HSSFSheet sheet = wb.createSheet(WorkbookUtil.createSafeSheetName("常住人口"));
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);
        Row row0 = sheet.createRow(0);
        row0.setHeight((short) 400);
        for (int i = 0; i < columnName.length; i++) {
            sheet.setColumnWidth(i, columnName[i].getBytes().length * 3 * 256);
            createCell(wb, row0, (short) 0, "导出游客数", cellStyle, font);
            createCell(wb, row0, (short) 1, regionEvaluatelList.size(), cellStyle, font);
        }
        Row row1 = sheet.createRow(1);
        row1.setHeight((short) 400);
        for (int i = 0; i < columnName.length; i++) {
            sheet.setColumnWidth(i, columnName[i].getBytes().length * 3 * 256);
            createCell(wb, row1, (short) i, columnName[i], cellStyle, font);
        }

        int in = 0;
        for (int i = 0; i < regionEvaluatelList.size(); i++) {
            sheet.setColumnWidth((short) 6, regionEvaluatelList.get(i).getAddress().getBytes().length * 420);
            sheet.setColumnWidth((short) 7, regionEvaluatelList.get(i).getRecentDate().getBytes().length * 300);
            String num = "";
            in++;
            ;
            Row row = sheet.createRow(i + 2);//"身份证", "姓名", "性别", "民族", "出生", "住址", "最近到馆时间"
            row.setHeight((short) 400);
            createCell(wb, row, (short) 0, in, cellStyle, font);
            createCell(wb, row, (short) 1, regionEvaluatelList.get(i).getName(), cellStyle, font);
            createCell(wb, row, (short) 2, regionEvaluatelList.get(i).getIdentityId(), cellStyle, font);

            if ("1".equals(regionEvaluatelList.get(i).getSex())) {
                createCell(wb, row, (short) 3, "男", cellStyle, font);
            } else {
                createCell(wb, row, (short) 3, "女", cellStyle, font);
            }
            createCell(wb, row, (short) 4, regionEvaluatelList.get(i).getNation() + "族", cellStyle, font);
            Date dateOfBirth = regionEvaluatelList.get(i).getDateOfBirth();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            createCell(wb, row, (short) 5, simpleDateFormat.format(dateOfBirth), cellStyle, font);
//            sheet.setColumnWidth(i, columnName[i].getBytes().length * 4 * 256);
            createCell(wb, row, (short) 6, regionEvaluatelList.get(i).getAddress(), cellStyle, font);
            String recentDate = regionEvaluatelList.get(i).getRecentDate();
//            sheet.setColumnWidth(i, columnName[i].getBytes().length * 3 * 256);
            createCell(wb, row, (short) 7, recentDate.substring(0, recentDate.length() - 2), cellStyle, font);
        }

        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1"));
        /*
         *设置强制下载不打开
         */
        response.setContentType("application/force-download");
        response.setCharacterEncoding("UTF-8");
        OutputStream os = response.getOutputStream();
        wb.write(os);
    }

    /**
     * 创建单元格
     *
     * @param row       行数
     * @param column    列数
     * @param cellValue 单元格内容
     * @author liukai
     */
    private static void createCell(Workbook wb, Row row, short column, Object cellValue, CellStyle cellStyle, Font font) {
        Cell cell = row.createCell(column);

        cell.setCellStyle(cellStyle);


        if (cellValue != null) {
            if ("java.lang.Integer".equals(cellValue.getClass().getName())) {
                DataFormat df = wb.createDataFormat();
                cellStyle.setDataFormat(df.getFormat("#,#0"));
                cell.setCellStyle(cellStyle);
                cell.setCellValue(Double.parseDouble(cellValue.toString()));
            } else {
                cell.setCellValue(String.valueOf(cellValue));
            }
        }


        cellStyle.setFont(font);
    }

    @PostMapping("/insert")
    @ResponseBody
    public List<String> insert(@RequestParam("uploadFile") MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();
        if (fileName.endsWith("xls")) {
            return identityService.input(mFile);
        } else if (fileName.endsWith("xlsx")) {
            return identityService.input(mFile);
        } else {
            List<String> error = new ArrayList<>();
            error.add("模版格式不对");
            return error;
        }
    }

    @GetMapping("toIdentityNow")
    public String identityList() {

        return "identityNow";
    }

    @ResponseBody
    @RequestMapping(value = "findOne", method = RequestMethod.GET)
    public Map<String, Object> findOne() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dayVisitors", dayVisitorsService.findTodayVisitorsAndSaveForHtml());
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "changCapacity", method = RequestMethod.GET)
    public void changCapacity(String id) {
        dayVisitorsService.update(id);
    }
}
